<template>
  <div class="page-container">
    <div class="page-header">
      <h2>个人资料</h2>
      <p>查看和管理您的个人账户信息</p>
    </div>
    
    <el-row :gutter="20">
      <!-- 左侧个人信息 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
        <el-card class="profile-card">
          <div class="profile-header">
            <div class="avatar-wrapper">
              <el-avatar :size="100" :src="userAvatar" />
            </div>
            <h3>{{ userInfo.realName }}</h3>
            <p>{{ userInfo.role === 'admin' ? '系统管理员' : userInfo.role === 'manager' ? '主管' : '员工' }}</p>
          </div>
          
          <div class="profile-info">
            <div class="info-item">
              <div class="info-label">用户名</div>
              <div class="info-value">{{ userInfo.username }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">邮箱</div>
              <div class="info-value">{{ userInfo.email || '未设置' }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">电话</div>
              <div class="info-value">{{ userInfo.phone || '未设置' }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧设置 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="18">
        <el-card class="tab-card">
          <el-tabs v-model="activeTab">
            <!-- 基本资料 -->
            <el-tab-pane label="基本资料" name="basic">
              <el-form
                ref="basicFormRef"
                :model="basicForm"
                :rules="basicRules"
                label-width="100px"
              >
                <el-form-item label="真实姓名" prop="realName">
                  <el-input v-model="basicForm.realName" placeholder="请输入真实姓名" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="basicForm.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                  <el-input v-model="basicForm.phone" placeholder="请输入电话" />
                </el-form-item>
                <el-form-item label="职位" prop="position">
                  <el-input v-model="basicForm.position" placeholder="请输入职位" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateBasicInfo" :loading="submitLoading">保存</el-button>
                  <el-button @click="resetBasicForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            
            <!-- 修改密码 -->
            <el-tab-pane label="修改密码" name="password">
              <el-form
                ref="passwordFormRef"
                :model="passwordForm"
                :rules="passwordRules"
                label-width="120px"
              >
                <el-form-item label="当前密码" prop="oldPassword">
                  <el-input 
                    v-model="passwordForm.oldPassword" 
                    type="password" 
                    placeholder="请输入当前密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input 
                    v-model="passwordForm.newPassword" 
                    type="password" 
                    placeholder="请输入新密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="确认新密码" prop="confirmPassword">
                  <el-input 
                    v-model="passwordForm.confirmPassword" 
                    type="password" 
                    placeholder="请再次输入新密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updatePassword" :loading="passwordLoading">修改密码</el-button>
                  <el-button @click="resetPasswordForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { updateUserProfile, updateUserPassword } from '@/api/auth'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const userStore = useUserStore()

// 获取用户信息
const userInfo = computed(() => userStore.userInfo || {})

// 头像图片
const userAvatar = computed(() => {
  return userInfo.value.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
})

// 表单引用
const basicFormRef = ref()
const passwordFormRef = ref()

// 加载状态
const submitLoading = ref(false)
const passwordLoading = ref(false)

// 当前激活的标签页
const activeTab = ref('basic')

// 基本信息表单
const basicForm = reactive({
  realName: '',
  email: '',
  phone: '',
  position: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})


// 基本信息表单验证规则
const basicRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 密码表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '未记录'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 初始化表单数据
const initFormData = () => {
  basicForm.realName = userInfo.value.realName || ''
  basicForm.email = userInfo.value.email || ''
  basicForm.phone = userInfo.value.phone || ''
  basicForm.position = userInfo.value.position || ''
}

// 重置基本信息表单
const resetBasicForm = () => {
  initFormData()
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.resetFields()
}


// 更新基本信息
const updateBasicInfo = async () => {
  try {
    await basicFormRef.value.validate()
    
    submitLoading.value = true
    const response = await updateUserProfile(basicForm)
    
    if (response.code === 200) {
      ElMessage.success('个人资料更新成功')
      // 更新 store 中的用户信息
      await userStore.getUserInfo()
    }
  } catch (error) {
    console.error('更新个人资料失败:', error)
    ElMessage.error('更新个人资料失败')
  } finally {
    submitLoading.value = false
  }
}

// 更新密码
const updatePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    passwordLoading.value = true
    const response = await updateUserPassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (response.code === 200) {
      ElMessage.success('密码修改成功')
      resetPasswordForm()
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败')
  } finally {
    passwordLoading.value = false
  }
}



// 初始化
onMounted(() => {
  // 确保已获取用户信息
  if (!userStore.userInfo) {
    userStore.getUserInfo()
  }
  
  initFormData()
})
</script>

<style lang="scss" scoped>
.page-header {
  margin-bottom: 20px;
  
  h2 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }
  
  p {
    color: #666;
    font-size: 14px;
  }
}

.profile-card {
  .profile-header {
    text-align: center;
    padding: 20px 0;
    
    .avatar-wrapper {
      margin-bottom: 16px;
    }
    
    h3 {
      margin: 8px 0;
      color: #333;
      font-size: 18px;
    }
    
    p {
      color: #666;
      margin: 0;
    }
  }
  
  .profile-info {
    padding: 16px 0;
    
    .info-item {
      display: flex;
      padding: 8px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .info-label {
        width: 80px;
        color: #666;
      }
      
      .info-value {
        flex: 1;
        color: #333;
      }
    }
  }
}

.tab-card {
  min-height: 400px;
}


@media (max-width: 768px) {
  .profile-card {
    margin-bottom: 20px;
  }
}
</style> 